<?php
namespace app\home\service;
use app\home\service\DoubanService;
use QL\QueryList;
use think\Exception;

class SearchProcessService
{

    public function getDoubanFilm($keyword) {
        $doubanService = new DoubanService();
        try{
            $suggestApi = str_replace('{q}', $keyword, DoubanService::API_SEARCH_SUGGEST);
            $suggestHash = md5('douban_' . $keyword);

            $films = cache($suggestHash);
            if (!is_array($films)) {
                $suggestResponse = $doubanService->request($suggestApi);
                if ($suggestResponse == false) {
                    return [];
                }
                $films = $doubanService->parseSearchSuggestResponse($suggestResponse);
                $suggest = array_pop($films);
                cache($suggestHash, $suggest, 86400);
            }

            if (empty($suggest)) {
                return [];
            }


            if (empty($suggest)) {
                return [];
            }
            $detailApi = str_replace('{id}', $suggest['id'], DoubanService::API_DETAIL);
            $detailHash = 'douban_' . md5($detailApi);

            $doubanService = new \app\home\service\DoubanService();
            $film = cache($detailHash);
            if (!is_array($film)) {
                $response = $doubanService->request($detailApi, null, 'get', [], false);
                if ($response) {
                    $film = $doubanService->parseDetailResponse($response);
                }
                cache($detailHash, $film, 86400);
                $film['id'] = $suggest['id'];
            } else {
                $film['id'] = $suggest['id'];
            }
        } catch (\Exception $exception) {
            return [];
        }

        return $film;
    }


    public function getDoubanPlayUrl($doubanId) {

        $detailApi = str_replace('{id}', $doubanId, DoubanService::API_DETAIL);
        $detailHash = 'douban_' . md5($detailApi);

        $doubanService = new \app\home\service\DoubanService();
        $film = cache($detailHash);
        if (!is_array($film)) {
            $response = $doubanService->request($detailApi, null, 'get', [], false);
            if ($response) {
                $film = $doubanService->parseDetailResponse($response);
            }
        }

        return $film['play_urls'] ?: [];
    }
}
